import random
import re

from flask_restful import Api, Resource, reqparse
from flask import Blueprint, jsonify, current_app

from models.user_model import User, db
from utils.JwtTools import JwtTool
from utils.RedisTools import RedisTool
from utils.SmsTools import SmsTool

user_bp=Blueprint('user_bp',__name__,url_prefix='/user')
api=Api(user_bp)

class SmsCode(Resource):
    """发送短信验证码"""
    def get(self,mobile):
        if not re.findall('^1[3-9]\d{9}$',mobile):
            return jsonify({
                'code':400,
                'msg':'手机号格式不正确'
            })
        code=str(random.randint(100000,999999))
        r=RedisTool().rds
        time=current_app.config.get('SMS_TIME')

        r.set(f'sms_{mobile}',code,ex=time*60)
        print(f'sms_{mobile}')
        # r.set('code_%s' % mobile,code,ex=time*60)
        r.close()
        sdk=SmsTool().send_code(mobile,code)
        if sdk:
            return jsonify({
                'code':200,
                'msg':'发送成功'
            })
        else:
            return jsonify({
                'code': 400,
                'msg': '发送失败'
            })
api.add_resource(SmsCode,'/sms/<mobile>')

class Login(Resource):
    def post(self):
        req=reqparse.RequestParser()
        req.add_argument('mobile',required=True)
        req.add_argument('code',required=True)
        args=req.parse_args()
        if not args['code']:
            return jsonify({
                'code': 400,
                'msg': '验证码不能为空'
            })
        r=RedisTool().rds
        # print(args["mobile"])
        code=r.get(f'sms_{args["mobile"]}')
        # print(f'sms_{args["mobile"]}')
        # code = r.get('code_%s' % args['mobile'])
        # print(code)
        r.close()
        if code.decode()!=args['code']:
            return jsonify({
                'code': 400,
                'msg': '验证码已过期'
            })
        user=User.query.filter_by(mobile=args['mobile']).first()
        if not user:

            username="游客"+args['mobile'][-4]

            u=User(
                mobile=args['mobile'],
                username=username
            )
            db.session.add(u)
            db.session.commit()
        user=User.query.filter_by(mobile=args['mobile']).first()
        token=JwtTool().gen_jwt(user,2*60*60)
        long_token=JwtTool().gen_jwt(user,24*60*60*15)
        return jsonify({
            'code':200,
            'msg':'登录成功',
            'token':token,
            'long_token':long_token
        })
api.add_resource(Login,'/login')



